package com.effectiv.gooruda.rest.api.controller;

import java.util.List;

import javax.validation.Valid;


import jodd.mail.ReceivedEmail;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import lombok.extern.slf4j.Slf4j;

import com.effectiv.gooruda.rest.api.domain.Email;
import com.effectiv.gooruda.rest.api.domain.EmailServerConfiguration;
import com.effectiv.gooruda.rest.api.exception.NoDataFoundException;
import com.effectiv.gooruda.rest.api.operation.EmailOperations;


@Slf4j
@Controller
@RequestMapping("/api/email")
public class EmailController implements EmailOperations {
	
	@Autowired
	@Qualifier("emailServiceImpl")
	private EmailOperations operations;
	
	
	
	@RequestMapping(value="/saveEmailServerConfiguration", method=RequestMethod.POST)
	@Override
	public  @ResponseBody EmailServerConfiguration saveEmailServerConfiguration(@Valid @RequestBody  EmailServerConfiguration config) {
		return operations.saveEmailServerConfiguration(config);
	}
	
	
	@RequestMapping(value="/findOneConfigurationByName/{name}", method=RequestMethod.GET)
	@Override
	public @ResponseBody EmailServerConfiguration findOneConfigurationByName(@PathVariable("name") String name) {
		EmailServerConfiguration config = operations.findOneConfigurationByName(name);
		
		if(config == null){
			throw new NoDataFoundException("No email server configuration exists for name - " + name);
		}
		
		return config;
	}
	
	
	
	@RequestMapping(value="/findAll", method=RequestMethod.GET)
	@Override
	public @ResponseBody  List<EmailServerConfiguration> findAll() {
		return operations.findAll();
	}
	
	
	
	
	@RequestMapping(value="/deleteConfigurationByName/{configName}", method=RequestMethod.DELETE )
	@Override
	public @ResponseBody void deleteConfigurationByName(@PathVariable("configName") String name) {
		operations.deleteConfigurationByName(name);
	}
	
	
	
	
	@RequestMapping(value="/sendmail/{configName}", method=RequestMethod.POST)
	@Override
	public @ResponseBody void send(@PathVariable("configName")  String configName, @Valid @RequestBody Email email) {
		operations.send(configName, email);
	}
	
	
	//TODO - Expose the API in doc and playground
	
	@Override
	@RequestMapping(value="/receivemail/{configName}", method=RequestMethod.POST)
	public @ResponseBody ReceivedEmail[] receive(@PathVariable("configName")  String configName) {
		
		return operations.receive(configName);
	}
	
	

}
